/*
 *    Copyright 2022 CManLH
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.lifeonwalden.ms.async.runner.service.impl;

import com.lifeonwalden.ms.async.runner.bean.AsyncRunnerItem;
import com.lifeonwalden.ms.async.runner.service.AsyncRunner;
import com.lifeonwalden.ms.async.runner.service.RunnerService;
import com.lifeonwalden.ms.async.runner.thread.Dispatcher;
import com.lifeonwalden.ms.common.logger.LoggerUtil;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.FormattedMessage;
import org.springframework.beans.factory.InitializingBean;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;

public class AsyncRunnerImpl implements AsyncRunner, InitializingBean {
    private final static Logger logger = LoggerUtil.getLogger(AsyncRunnerImpl.class);

    private ConcurrentHashMap<Integer, RunnerService> runner = new ConcurrentHashMap<>();

    private BlockingQueue<AsyncRunnerItem> queue;

    // 消息队列大小
    private int msgBufferSize = 128;

    // 消息队列大小
    private int secondLevelMsgBufferSize = 1024;

    // 最大线程数
    private int maxThread;

    // 最大空闲线程数
    private int maxIdelThread;

    // 轮询间隔时间, 分钟计
    private int poolingInterval;

    @Override
    public void runAsync(AsyncRunnerItem item) {
        try {
            queue.put(item);
        } catch (InterruptedException e) {
            logger.error(new FormattedMessage("Failed to accept msg : {}", LoggerUtil.convertValueToString(logger, item)), e);
        }
    }

    @Override
    public void registerRunner(Integer id, RunnerService runnerService) {
        if (runner.containsKey(id)) {
            throw new RuntimeException("Duplicated register runner service of ".concat(String.valueOf(id)));
        }

        runner.putIfAbsent(id, runnerService);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        queue = new ArrayBlockingQueue<>(msgBufferSize);

        new Thread(new Dispatcher(maxThread, maxIdelThread, poolingInterval, secondLevelMsgBufferSize, queue, runner)).start();
    }

    public AsyncRunnerImpl setMsgBufferSize(int msgBufferSize) {
        this.msgBufferSize = msgBufferSize;

        return this;
    }

    public AsyncRunnerImpl setSecondLevelMsgBufferSize(int secondLevelMsgBufferSize) {
        this.secondLevelMsgBufferSize = secondLevelMsgBufferSize;

        return this;
    }

    public AsyncRunnerImpl setMaxThread(int maxThread) {
        this.maxThread = maxThread;

        return this;
    }

    public AsyncRunnerImpl setMaxIdelThread(int maxIdelThread) {
        this.maxIdelThread = maxIdelThread;

        return this;
    }

    public AsyncRunnerImpl setPoolingInterval(int poolingInterval) {
        this.poolingInterval = poolingInterval;

        return this;
    }
}